<script setup>
import { handleEmoji, parseEmoji, textHandle, uniqueBy } from '@/utils/dialog-utils'
import useUser from '@/store/user.js'
import { addMsgTextTag, deleteMsgTextTag, emojiReply, emojiReplyDel } from '@/assets/api/message.js'

const props = defineProps({
  message: Object,
  disabledOperation: Boolean,
  disabledEmoji: Boolean,
  disabledTag: Boolean,
  isCurrentUser: Boolean,
  options: {
    type: Object,
    default: () => ({
      shieldTask: true,
    }),
  },
})

const slots = useSlots()

const userStore = useUser()

const { id, content, files, metaData, clientFiles, mentionUsers } = toRefs(props.message)

const textContent = computed(() => {
  if (!content.value) return []
  return content.value.split(/\n/)
})

const mentionMe = computed(() => {
  if (!mentionUsers?.value) return false
  return JSON.parse(mentionUsers.value)?.some((i) => i === userStore.userId)
})

const fileList = computed(() => {
  if (clientFiles?.value && clientFiles.value.length) {
    return clientFiles.value
  } else {
    return files.value || []
  }
})

function handleTagClick(item) {
  ;(item.details.some((i) => i.userId === userStore.userId) ? deleteMsgTextTag : addMsgTextTag)(id.value, item)
}

// 除了默认表情，其他表情去掉背景
const hasOtherEmoji = computed(() => {
  return (
    !fileList.value.length &&
    textContent.value.every((i) => {
      const emojiResult = parseEmoji(i)
      return emojiResult.has && !emojiResult.prev && !emojiResult.next && emojiResult.target.type !== 'default'
    })
  )
})

// 表情评论
const reactions = computed(() => {
  const arr = []
  metaData.value.reactions?.forEach((i) => {
    const { emoji } = handleEmoji(i.emojiName)
    if (emoji) {
      const index = arr.findIndex((j) => i.emojiName === j.name)
      if (index === -1) {
        arr.push({
          name: i.emojiName,
          src: emoji.url,
          msgId: i.msgId,
          channelId: i.channelId,
          data: [i],
        })
      } else {
        arr[index].data.push(i)
      }
    }
  })
  return arr.map((item) => {
    item.data = uniqueBy(item.data, 'userId')
    return item
  })
})

function handleEmojiComment(emoji) {
  const target = emoji.data.find((i) => i.userId === userStore.userId)
  if (target) {
    emojiReplyDel(target.id)
  } else {
    emojiReply({
      msgId: emoji.msgId,
      channelId: emoji.channelId,
      emojiName: emoji.name,
    })
  }
}

// 收到
function receiveMsg() {
  const target = reactions.value.find((i) => i.name === 'default_OK')
  const emoji = target && target.data.find((i) => i.userId === userStore.userId)
  if (emoji) {
    emojiReplyDel(emoji.id)
  } else {
    emojiReply({
      msgId: props.message.id,
      channelId: props.message.channelId,
      emojiName: 'default_OK',
    })
  }
}

function buildTagStyle(color) {
  return {
    '--color': `var(${color})`,
    '--border': `1px solid var(${color}-light-8)`,
    '--background': `var(${color}-light-9)`,
  }
}
</script>

<template>
  <div
    class="basic-message"
    :class="{
      'transparent-bg': (hasOtherEmoji || slots.custom) && !metaData.textTags?.length && !reactions.length,
      'current-user': props.isCurrentUser,
    }">
    <slot name="custom">
      <template v-if="content">
        <div
          class="message-box-text-color"
          v-html="textHandle(item, index, props.options)"
          v-for="(item, index) in textContent"
          :key="index"></div>
        <span class="message-edited" v-if="metaData.status.editFlag">(已编辑)</span>
      </template>
      <div class="file-list" v-if="fileList.length">
        <TextFileCard
          v-for="(item, index) in fileList"
          :key="index"
          :file="item"
          :loading="!item.id"
          adaptive
          file-view
          download></TextFileCard>
      </div>
    </slot>

    <!--表情评论-->
    <div class="emoji-comment-list" v-if="!props.disabledEmoji && reactions.length">
      <div
        class="emoji-comment"
        v-for="(item, index) in reactions"
        :key="index"
        @click="!props.disabledOperation && handleEmojiComment(item)">
        <div class="comment-icon">
          <SvgIcon :src="item.src" size="16" />
        </div>
        <span class="comment-user" v-for="(user, userIndex) in item.data" :key="userIndex">
          {{ userIndex ? ', ' : '' }}{{ user.userName }}
        </span>
      </div>
    </div>

    <!--标签-->
    <div class="tag-list" v-if="!props.disabledTag && metaData.textTags?.length">
      <div
        class="tag-item"
        v-for="(item, index) in metaData.textTags"
        :key="index"
        :style="buildTagStyle(item.color)"
        @click="handleTagClick(item)">
        {{ item.tag }} {{ item.count }}
      </div>
    </div>
    <div v-if="!props.disabledOperation && mentionMe" class="basic-message-mention">
      <div @click.stop="receiveMsg">
        <img src="@/assets/image/emoji-data/cartoon/1_OK.png" alt="" width="20" height="20" />
        收到
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.basic-message {
  display: inline-block;
  font-size: 14px;
  min-height: 41px;
  padding: 10px;
  border-radius: 6px;
  background-color: var(--elp-color-info-light-9);
  text-align: left;
  max-width: 100%;
  flex-shrink: 0;
  &.transparent-bg {
    padding: 0;
    background-color: transparent;
  }
  .message-box-text-color {
    white-space: pre-wrap;
  }
  .message-edited {
    font-size: 12px;
    color: #999999;
  }
  .reply-message {
    border-radius: 8px;
    margin-bottom: 5px;
  }
  .emoji-comment-list {
    @include use-flex();
    flex-wrap: wrap;
    .emoji-comment {
      @include use-flex(center);
      cursor: pointer;
      flex-wrap: wrap;
      padding: 4px 10px;
      border-radius: 13px;
      color: var(--elp-color-info);
      margin-right: 6px;
      margin-top: 10px;
      background: rgba(189, 191, 195, 0.45);
      .comment-icon {
        display: inline-flex;
        align-items: center;
        &:after {
          content: '';
          display: inline-block;
          margin: 0 4px;
          width: 1px;
          height: 12px;
          background: #999999;
        }
      }
      .comment-user {
        font-size: 12px;
      }
    }
  }
  .tag-list {
    padding-top: 5px;
    @include use-flex();
    flex-wrap: wrap;
    .tag-item {
      cursor: pointer;
      padding: 1px 8px;
      font-size: 11px;
      border-radius: 6px;
      margin-right: 3px;
      margin-bottom: 3px;
      color: var(--color);
      border: var(--border);
      background: var(--background);
    }
  }
  .file-list {
    padding: 5px 0;
  }
  .basic-message-mention {
    cursor: pointer;
    min-width: 150px;
    border-top: 1px solid #d4d8e0;
    padding-top: 10px;
    user-select: none;
    & > div {
      @include use-flex(center, center);
      color: #0d53ff;
      text-align: center;
    }
  }
}
</style>
